package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.dto.ShouJiFaMbDTO;
import com.ruoyi.system.mapper.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;

/**
 * 排行榜Controller
 *   我曾经走过多远的路
 * @author 风离
 * @date 2022-05-27
 */
@RestController
@RequestMapping("/system/leaderboard")
public class LeaderboardController extends BaseController
{


    @Resource
    private LeaderboardMapper leaderboardMapper;

    @Resource
    private LeaderboardTypeMapper leaderboardTypeMapper;

    @Resource
    private OrderListMapper orderListMapper;



    @PostMapping("/disableShouJi")
    public AjaxResult disableShouJi()
    {
       int disable = orderListMapper.disableShouji();

        return AjaxResult.success("失效的二级订单数量： "+disable);
    }

    @PostMapping("/disablePhb")// 是某个时段的排行榜失效
    public AjaxResult disablePhb(@RequestParam("startTime")String startTime,
                                 @RequestParam("endTime")String endTime,
                                 @RequestParam("type")Integer type,
                                 @RequestParam("isDisable")Integer isDisable)
    {
        int i = leaderboardMapper.disablePhb(startTime,endTime,type,isDisable);
        if(i>0)
        {
            return AjaxResult.success("排行榜失效成功！");
        }
        else
        {
            return AjaxResult.error("排行榜失效失败！");
        }
    }

    @Resource
    UserMapper userMapper;

    @Resource
    private ProfitJifenMapper profitJifenMapper;

    @PostMapping("/shoujiFaMb") //收集发放mb
    @Transactional
    public AjaxResult shouJiFaMb( @RequestBody ShouJiFaMbDTO shouJiFaMbDTO)
    {
         logger.info("收集发放mb {}", JSONObject.toJSONString(shouJiFaMbDTO));
        shouJiFaMbDTO.getMbList().forEach((k,v)-> {
                    User user = userMapper.selectUserById(k);
                    if (user != null) {
                       Double newV =v/100.0;
                       //对newV进行四舍五入
                        BigDecimal bigDecimal = new BigDecimal(newV);
                        BigDecimal bigDecimal1 = bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP);
                        newV = bigDecimal1.doubleValue();


                        user.setMb(user.getMb() + newV.intValue());
                        userMapper.updateUser(user);
                        ProfitJifen profitJifen =new ProfitJifen();
                        profitJifen.setUserId(k);
                        profitJifen.setMoney(BigDecimal.valueOf(user.getMb()));
                        profitJifen.setChange(bigDecimal1);
                        profitJifen.setType(1);
                        profitJifen.setAdminId(0L);
                        profitJifen.setCreator(0L);
                        profitJifen.setIfMb(1);

                        int i1 = profitJifenMapper.insertProfitJifen(profitJifen);
                        logger.info("更新用户Mb记录： {}",i1);

                    }else {
                        logger.info("用户不存在： {}",k);
                       throw new RuntimeException();
                    }

                });

         disablePhb(shouJiFaMbDTO.getStart(),shouJiFaMbDTO.getEnd(),2,1);


        return AjaxResult.success();
    }

    @PostMapping("/listByType") //某个排行榜的具体数据
    public AjaxResult listByType(@RequestParam("type") Integer type, @RequestParam("page") Integer page,
                                 @RequestParam("size") Integer size,
                                 @RequestParam("start") String start,
                                 @RequestParam("end")String end
                                 )
    {
        logger.info("type: {},page: {},size: {},start: {},end: {}",type,page,size,start,end);
        //收集单独算
        if(type==2)
        {
            HashMap<String,Integer> sortMap =new HashMap<>();

            List<OrderList> orderLists = orderListMapper.selectShouji(0,start,end);
            if(orderLists.size()!=0)
            {

                orderLists.forEach(
                        o-> sortMap.merge(String.valueOf(o.getUserId()==null?0:o.getUserId()), o.getIfCollect(), Integer::sum)
                );
                Map<String, Integer> newMap= sortMapByValues(sortMap);
                List<Leaderboard> leaderboards =new ArrayList<>();
                AtomicInteger count = new AtomicInteger();
                newMap.forEach((k,v)->{
                    Leaderboard leaderboard =new Leaderboard();
                    User user=userMapper.selectUserById(k);
                    if(user!=null)
                    {
                        leaderboard.setLeaderboardName("收集");
                        leaderboard.setType(3);
                        leaderboard.setUserId(k);
                        leaderboard.setUserAvatar(user.getHeadimg());
                        leaderboard.setUserName(user.getNickname());
                        leaderboard.setJf(v);
                        leaderboards.add(leaderboard);
                    }
                    count.getAndIncrement();
                });

                return AjaxResult.success(leaderboards);
            }
            else
            {
                return AjaxResult.error("没有收集订单！");
            }

        }


        PageHelper.startPage(page, size);
        List<Leaderboard> list = leaderboardMapper.listByType(type,start,end);

        return AjaxResult.success(new PageInfo<>(list));
    }

    public static <K extends Comparable, V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> aMap) {
        HashMap<K, V> finalOut = new LinkedHashMap<>();
        aMap.entrySet()
                .stream()
                .sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
                .collect(Collectors.toList()).forEach(ele -> finalOut.put(ele.getKey(), ele.getValue()));
        return finalOut;
    }

    /**
     * 查询排行榜列表
     */


    @PostMapping("/getLeaderboard")
    public AjaxResult getLeaderboard()
    {
        List<LeaderboardType> leaderboardList = leaderboardTypeMapper.selectList();
        return AjaxResult.success(leaderboardList);
    }


//    @PostMapping("/changeLeaderboardSandE")
//    public AjaxResult changeLeaderboardSandE(@RequestBody LeaderboardType leaderboardType)
//    {
//        leaderboardTypeMapper.updateById(leaderboardType);
//        return AjaxResult.success();
//    }

    @PostMapping("edit")
    public AjaxResult edit(@RequestBody LeaderboardType leaderboard)
    {
        int i = leaderboardTypeMapper.updateById(leaderboard);
        logger.info("修改排行榜："+i);
        return AjaxResult.success("修改成功");
    }



    /**
     *  统计用户串串乐情况
     *
     *   1 获得全局奖 个数
     *   2 统计 他抽奖次数
     *   3 统计 他消费金额
     *
     *   4 达到门槛加金额 是否分解 减分
     *
     *
     *   第一步找出参与排行榜的 二级分类ID
     *
     *   第二步找出用户购买该盒子的记录 并统计 group by user_id
     *
     */
//    @GetMapping("/total")
//    public AjaxResult  total(@RequestParam("typeId")Integer typeId)
//    {
//        Leaderboard leaderboard =new Leaderboard();
//        leaderboard.setLeaderType(Long.valueOf(typeId));
//        List<Leaderboard> list = leaderboardService.selectLeaderboardList(leaderboard);
//        Integer[] goodIds = new Integer[list.size()];
//        for (int i = 0; i < list.size(); i++) {
//            goodIds[i] = Math.toIntExact(list.get(i).getGoodId());
//        }
//        Integer award = leaderboardTypeService.selectLeaderboardTypeById(Long.valueOf(typeId)).getAddAward();
//        Integer all = leaderboardTypeService.selectLeaderboardTypeById(Long.valueOf(typeId)).getAllAward();
//        if(goodIds.length==0)
//        {
//            return AjaxResult.error("参与排行的列表为空！");
//        }
//        if (typeId==1)
//        {
//            Map map =new HashMap<String,Object>();
//            map.put("leaderboardName","串串乐榜");
//            logger.info(Arrays.toString(goodIds)+"");
//            List<LeaderboardDTO> leaderboardDTOList = leaderboardService.selectLeaderboardType1(award,goodIds,all);
//            map.put("list", leaderboardDTOList);
//            return AjaxResult.success(map);
//
//        }else if(typeId==2)
//        {
//            Map map =new HashMap<String,Object>();
//            map.put("leaderboardName","收集榜");
//
//            List<LeaderboardDTO> leaderboardDTOList = leaderboardService.selectLeaderboardType2(award,goodIds);
//            map.put("list", leaderboardDTOList);
//            return AjaxResult.success(map);
//
//        }else if(typeId==3)
//        {
//
//
//        }else {
//            return AjaxResult.error("排行榜类型错误~");
//        }
//        return AjaxResult.error("排行榜类型错误~");
//    }

//
//
//
//
//
//    /**
//     *  查看某个排行榜的排名情况
//     *  typeId : 1 2 3
//     *  前 100 名 根据奖励积分倒叙排列
//     */
//
//    @GetMapping("/sort")
//    public AjaxResult  sort(@RequestParam("typeId")Integer typeId)
//    {
//        if (typeId==1)
//        {
//
//
//        }else if(typeId==2)
//        {
//
//        }else if(typeId==3)
//        {
//
//        }else {
//            return AjaxResult.error("排行榜类型错误~");
//        }
//        return AjaxResult.error("排行榜类型错误~");
//    }
//
//
//    /**
//     * 查询排行榜列表
//     */
//    @PreAuthorize("@ss.hasPermi('system:leaderboard:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(Leaderboard leaderboard)
//    {
//        startPage();
//        List<Leaderboard> list = leaderboardService.selectLeaderboardList(leaderboard);
//        return getDataTable(list);
//    }
//
//    /**
//     * 导出排行榜列表
//     */
//    @PreAuthorize("@ss.hasPermi('system:leaderboard:export')")
//    @Log(title = "排行榜", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, Leaderboard leaderboard)
//    {
//        List<Leaderboard> list = leaderboardService.selectLeaderboardList(leaderboard);
//        ExcelUtil<Leaderboard> util = new ExcelUtil<Leaderboard>(Leaderboard.class);
//        util.exportExcel(response, list, "排行榜数据");
//    }
//
//    /**
//     * 获取排行榜详细信息
//     */
//    @PreAuthorize("@ss.hasPermi('system:leaderboard:query')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id)
//    {
//        return AjaxResult.success(leaderboardService.selectLeaderboardById(id));
//    }
//
//    /**
//     * 新增排行榜
//     */
//    @PreAuthorize("@ss.hasPermi('system:leaderboard:add')")
//    @Log(title = "排行榜", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody Leaderboard leaderboard)
//    {
//        return toAjax(leaderboardService.insertLeaderboard(leaderboard));
//    }
//
//    /**
//     * 修改排行榜
//     */
//    @PreAuthorize("@ss.hasPermi('system:leaderboard:edit')")
//    @Log(title = "排行榜", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody Leaderboard leaderboard)
//    {
//        return toAjax(leaderboardService.updateLeaderboard(leaderboard));
//    }
//
//    /**
//     * 删除排行榜
//     */
//    @PreAuthorize("@ss.hasPermi('system:leaderboard:remove')")
//    @Log(title = "排行榜", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids)
//    {
//        return toAjax(leaderboardService.deleteLeaderboardByIds(ids));
//    }
}
